/*!
文本内容提取模块
 - 针对pptx, docx, xlsx进行的文本内容提取
 - 提取的文本保存为idx.rabbit.txt
 - crate dotext = "0.1"
 - pdf目前没有找到合适的crate
*/
use crate::*;
use anyhow::anyhow;
use dotext::*;
use std::io::Read;
use std::path::PathBuf;

#[cfg(feature = "tracelog")]
use tracing::error;
#[cfg(feature = "rotatelog")]
use log::error;

pub fn extract_as_text(root:&PathBuf, source :PathBuf, save_as: &PathBuf)->Result<()> {
    let ext = source
        .extension()
        .unwrap_or_default()
        .to_string_lossy();

    let ext = ext.to_lowercase(); //.as_str();        
    let not_do: Vec<&str> = vec!["jpg", "jpeg", "png", "svg","tar","zip","rar", "exe",""];
    if not_do.contains(&ext.as_str()) {
        return Result::Ok(());
    }

    match ext.as_str() {
        "docx" => {
            extract_docx(&source, &save_as)?;
        },
        "pptx" => {
            extract_pptx(&source, &save_as)?;
        },
        "xlsx" => {
            extract_xlsx(&source, &save_as)?;
        },
        "pdf" => {
            extract_pdf(root, &source, &save_as)?
        },       
        _ => { error!("no implyment for {}",ext); },
    }
    Result::Ok(())
}

fn extract_docx(source :&PathBuf, save_as:&PathBuf)->Result<()>{
    let mut file = Docx::open(source)?;
    let mut buf = String::new();
    let usize = file.read_to_string(&mut buf)?;
    if usize > 0 {
        std::fs::write(save_as, buf)?;    
    } else {
        error!("error to extract docx");
    }
    Ok(())
}

fn extract_xlsx(source :&PathBuf, save_as:&PathBuf)->Result<()>{
    let mut file = dotext::Xlsx::open(source)?;
    let mut buf = String::new();
    let usize = file.read_to_string(&mut buf)?;
    if usize > 0 {
        std::fs::write(save_as, buf)?;    
    } else {
        error!("error to extract xlsx");
    }
    Ok(())
}

fn extract_pptx(source :&PathBuf, save_as:&PathBuf)->Result<()>{
    let mut file = dotext::Pptx::open( source )?;
    let mut buf = String::new();
    let usize = file.read_to_string(&mut buf)?;
    if usize > 0 {
        std::fs::write(save_as, buf)?;    
    } else {
        error!("error to extract pptx");
    }
    Ok(()) 
}

fn extract_pdf(root:&PathBuf, source :&PathBuf, save_as:&PathBuf)->Result<()>{
    let script = root.join("bin").join("extract-pdf.py");
    if script.exists() {
        let encoded_in_name = urlencoding::encode(source.display().to_string().as_str()).to_string();
        let encoded_out_name = urlencoding::encode(save_as.display().to_string().as_str()).to_string();
        std::process::Command::new("python3")
            .arg(script)
            .arg(encoded_in_name)
            .arg(encoded_out_name)            
            .spawn()?;
    } else {
        bail!("Error, script is not exist");
    }
    Result::Err(anyhow!("no implement"))    
}

